<template>
  <el-dialog
    v-if="load"
    title="采购记录"
    v-model="visible"
    align-center
    width="1200"
    @close="handleClose"
    draggable
    :z-index="2000"
  >
    <div class="dialog-content1">
      <el-tabs v-model="activeName" @tab-change="handleChange">
        <el-tab-pane label="历史采购记录" :name="1">
          <div class="flex">
            <div class="flex items-center mr-2">
              订单状态：
              <el-select
                class="!w-[160px]"
                v-model="formData.audit_status"
                collapse-tags
                placeholder="请选择"
                clearable
                multiple
                :teleported="false"
              >
                <el-option
                  v-for="item in purchaseStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="flex items-center mr-2">
              <span class="w-[100px]">采购单号：</span
              ><multi-input
                v-model="formData.purchase_no"
                placeholder="批量搜索,一行一个"
                class="!w-[160px]"
              ></multi-input>
            </div>
            <el-button type="primary" @click="getPurchaseProcessHistoryList"
              >查询</el-button
            >
          </div>
          <div class="flex py-2">
            <div class="mr-2">SKU: {{ formData.sku }}</div>
            <div class="mr-2 w-[320px]">
              <VText title="产品名称" :value="formData.spu_cn_title" :line="2"></VText>
            </div>
            <div class="ml-auto mr-2">采购中：{{ product_info.purchase_num_total }}</div>
            <div class="">历史入库总量：{{ product_info.inbound_num_total }}</div>
          </div>
          <vxe-grid
            class="mytable-scrollbar"
            ref="tableRef"
            v-bind="tableOptionsPurchase"
          >
          </vxe-grid>
        </el-tab-pane>
        <el-tab-pane label="供应商历史报价" :name="2">
          <vxe-grid
            class="mytable-scrollbar"
            ref="tableRef"
            v-bind="tableOptionsSupplier"
          ></vxe-grid>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script setup lang="jsx">
import { getPurchaseHistory } from "@/api/index.js";
import { supplierHistory } from "../api.js";
import { reactive, toRefs } from "vue";
import { purchaseStatusOptions } from "../data.js";

const activeName = ref(1);

const data = reactive({
  product_info: {},
  formData: {
    audit_status: "",
    purchase_no: "",
  },
  visible: false,
  load: false,
});

const { product_info, formData, visible, load } = toRefs(data);
// 打开弹窗
const open = async (data) => {
  console.log(data);
  if (!load.value) {
    load.value = true;
    await 1;
  }
  visible.value = true;
  activeName.value = 1;
  formData.value.sku = data.sku || -1;
  formData.value.sku_id = data.id || -1;
  formData.value.spu_cn_title = data.spu_cn_title;
  formData.value.is_auth = 2;
  getPurchaseProcessHistoryList();
};

const getPurchaseProcessHistoryList = (data) => {
  tableOptionsPurchase.data = [];
  tableOptionsPurchase.loading = true;
  getPurchaseHistory(formData.value)
    .then((res) => {
      tableOptionsPurchase.data = res?.data?.list || [];
      const inbound_num_total = tableOptionsPurchase.data.reduce((acc, cur) => {
        return acc + Number(cur.inbound_num);
      }, 0);
      const purchase_num_total = tableOptionsPurchase.data.reduce((acc, cur) => {
        return acc + Number(cur.purchase_num - cur.deliver_num);
      }, 0);

      product_info.value = {
        sku: res.data.sku,
        sku_name: res.data.sku_name,
        total: res.data.total,
        inbound_num_total,
        purchase_num_total,
      };
    })
    .finally(() => {
      tableOptionsPurchase.loading = false;
    });
};
const getSupplierHistory = (data) => {
  tableOptionsSupplier.data = [];
  tableOptionsSupplier.loading = true;
  supplierHistory(data)
    .then((res) => {
      tableOptionsSupplier.data = res?.data || [];
    })
    .finally(() => {
      tableOptionsSupplier.loading = false;
    });
};

const handleChange = (val) => {
  if (val === 1) {
    getPurchaseProcessHistoryList({ sku: formData.value?.sku || -1 });
  } else if (val === 2) {
    getSupplierHistory({ sku_id: formData.value?.sku_id, pageSize: 1000, pageNum: 1 });
  }
};
const tableOptionsPurchase = reactive({
  round: true,
  height: "500",
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  loading: false,
  data: [],
  columns: [
    {
      title: "采购单号",
      field: "purchase_no",
      width: "160",
      fixed: "left",
      slots: {
        header: ({ row }) => {
          return (
            <div>
              采购单号
              <br />
              采购状态
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div>{row.purchase_no}</div>
              <div>{row.audit_status_name}</div>
            </div>
          );
        },
      },
    },
    {
      title: "供应商",
      field: "supplier_name",
      minWidth: "150",
      slots: {
        header: ({ row }) => {
          return (
            <div>
              供应商名称
              <br />
              供应商类型
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <dataAuthority
                auth="supplier_name"
                value={row.supplier_name}
                default_value={row.supplier_code}
              ></dataAuthority>
              <div>{row.purchase_type_name}</div>
            </div>
          );
        },
      },
    },
    {
      title: "国家",
      field: "country_name",
      minWidth: "120",
      slots: {
        header: ({ row }) => {
          return (
            <div>
              国家
              <br />
              发货仓
              <br />
              目的仓
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div>{row.country_name}</div>
              <div>{row.demand_destination_warehouse_name}</div>
              <div>{row.destination_warehouse_name}</div>
            </div>
          );
        },
      },
    },
    {
      title: "数量",
      field: "number",
      minWidth: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <div class="mr-2">
                  需求：
                  <dataAuthority
                    auth="purchase_num"
                    value={row.demand_num}
                  ></dataAuthority>
                </div>
                <div>
                  下单：
                  <dataAuthority
                    auth="purchase_num"
                    value={row.purchase_num}
                  ></dataAuthority>
                </div>
              </div>
              <div class="flex">
                <div class="mr-2">
                  收货：
                  <dataAuthority
                    auth="purchase_num"
                    value={row.deliver_num}
                  ></dataAuthority>
                </div>
                <div>
                  入库：
                  <dataAuthority
                    auth="purchase_num"
                    value={row.inbound_num}
                  ></dataAuthority>
                </div>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "产品单价",
      field: "total_price",
      width: "100",
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              产品单价
              <el-tooltip
                class="box-item"
                effect="dark"
                content="退税：取采购含税价；不退税：取采购未税报价"
                placement="top-start"
              >
                <svg-icon icon-class="hint_cover2"></svg-icon>
              </el-tooltip>
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              {row.is_drawback == 1 && (
                <dataAuthority auth="unit_price" value={row.unit_price}></dataAuthority>
              )}
              {row.is_drawback == 2 && (
                <dataAuthority
                  auth="purchase_untaxed_price"
                  value={row.unit_price_tax}
                ></dataAuthority>
              )}
            </div>
          );
        },
      },
    },
    {
      title: "运费成本分摊",
      field: "tracking_price",
      width: "100",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <dataAuthority
                auth="unit_tracking_price"
                value={row.tracking_price}
              ></dataAuthority>
            </div>
          );
        },
      },
    },
    // {
    //   title: "加权平均价",
    //   field: "move_average_price",
    //   width: "100",
    //   slots: {
    //     default: ({ row }) => {
    //       return (
    //         <div>
    //           <dataAuthority
    //             auth="unit_purchase_price"
    //             value={row.move_average_price}
    //           ></dataAuthority>
    //         </div>
    //       );
    //     },
    //   },
    // },
    {
      title: "是否退税",
      field: "is_drawback_name",
      width: "100",
    },
    {
      title: "供应商报价",
      field: "unit_price_price",
      width: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                采购未税报价:
                <dataAuthority auth="unit_price" value={row.unit_price}></dataAuthority>
              </div>
              <div>
                采购未税价:
                <dataAuthority
                  auth="purchase_untaxed_price"
                  value={row.unit_untaxed_price}
                ></dataAuthority>
              </div>
              <div>
                采购含税价:
                <dataAuthority
                  auth="unit_price_tax"
                  value={row.unit_price_tax}
                ></dataAuthority>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "采购员",
      field: "purchase_user_name",
      minWidth: "150",
      slots: {
        header: ({ row }) => {
          return (
            <div>
              采购员
              <br />
              计划人员
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div>{row.purchase_user_name}</div>
              <div>{row.plan_user_name}</div>
            </div>
          );
        },
      },
    },
    {
      title: "需求部门",
      field: "department_name",
      width: "100",
    },
    {
      title: "下单时间",
      field: "create_time",
      minWidth: "160",
      slots: {
        header: ({ row }) => {
          return (
            <div>
              下单时间
              <br />
              预计到货时间
              <br />
              最后入库时间
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div>{row.create_time}</div>
              <div>{row.expect_delivery_time}</div>
              <div>{row.inbound_time}</div>
            </div>
          );
        },
      },
    },
    {
      title: "采购耗时",
      field: "purchase_date",
      width: "160",
      slots: {
        header: ({ row }) => {
          return (
            <div>
              采购耗时
              <br />
            </div>
          );
        },
        default: ({ row }) => {
          return <div>{row.purchase_date || "--"}</div>;
        },
      },
    },
  ],
});
const tableOptionsSupplier = reactive({
  round: true,
  height: 569,
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  loading: false,
  data: [],
  columns: [
    {
      title: "是否默认供应商",
      field: "is_default_supplier_text",
      width: "120",
      fixed: "left",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span class={sameNumber(row, "is_default_supplier")}>
                {row.old_is_default_supplier == 1 ? "是" : "否"} →
              </span>
              <span class={diffNumber(row, "is_default_supplier")}>
                {row.is_default_supplier == 1 ? "是" : "否"}
              </span>
            </div>
          );
        },
      },
    },
    {
      title: "供应商名称",
      field: "supplier_name",
      minWidth: "150",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <dataAuthority
                auth="supplier_name"
                value={row.supplier_name}
                default_value={row.supplier_code}
              ></dataAuthority>
            </div>
          );
        },
      },
    },
    { title: "采购类型", field: "purchase_type_text", width: "110" },
    {
      title: "是否退税",
      field: "is_refund_tax",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span class={sameNumber(row, "is_refund_tax")}>
                {row.old_is_refund_tax == 2 ? "退税" : "不退税"} →
              </span>
              <span class={diffNumber(row, "is_refund_tax")}>
                {row.is_refund_tax == 2 ? "退税" : "不退税"}
              </span>
            </div>
          );
        },
      },
    },
    {
      title: "采购未税报价",
      field: "unit_price",
      width: "110",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span class={sameNumber(row, "unit_price")}>
                <dataAuthority
                  auth="unit_price"
                  value={row.old_unit_price || "/"}
                ></dataAuthority>{" "}
                →
              </span>
              <dataAuthority
                class={diffNumber(row, "unit_price")}
                auth="unit_price"
                value={row.unit_price}
              ></dataAuthority>
            </div>
          );
        },
      },
    },
    {
      title: "采购含税价",
      field: "unit_price_tax",
      width: "110",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span class={sameNumber(row, "unit_price_tax")}>
                <dataAuthority
                  auth="unit_price_tax"
                  value={row.old_unit_price_tax || "/"}
                ></dataAuthority>{" "}
                →{" "}
              </span>
              <dataAuthority
                class={diffNumber(row, "unit_price_tax")}
                auth="unit_price_tax"
                value={row.unit_price_tax}
              ></dataAuthority>
            </div>
          );
        },
      },
    },
    {
      title: "采购未税价",
      field: "purchase_untaxed_price",
      width: "110",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span class={sameNumber(row, "purchase_untaxed_price")}>
                <dataAuthority
                  auth="purchase_untaxed_price"
                  value={row.old_purchase_untaxed_price || "/"}
                ></dataAuthority>{" "}
                →{" "}
              </span>
              <dataAuthority
                class={diffNumber(row, "purchase_untaxed_price")}
                auth="purchase_untaxed_price"
                value={row.purchase_untaxed_price}
              ></dataAuthority>
            </div>
          );
        },
      },
    },
    {
      title: "供应商税点",
      field: "tax_rate",
      width: "110",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span class={sameNumber(row, "tax_rate")}>
                <dataAuthority
                  auth="tax_rate"
                  value={row.old_tax_rate || "/"}
                ></dataAuthority>{" "}
                →{" "}
              </span>
              <dataAuthority
                class={diffNumber(row, "tax_rate")}
                auth="tax_rate"
                value={row.tax_rate}
              ></dataAuthority>
            </div>
          );
        },
      },
    },
    {
      title: "发票税点",
      field: "invoice_tax_rate",
      width: "110",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span class={sameNumber(row, "invoice_tax_rate")}>
                <dataAuthority
                  auth="tax_rate"
                  value={row.old_invoice_tax_rate || "/"}
                ></dataAuthority>{" "}
                →{" "}
              </span>
              <dataAuthority
                class={diffNumber(row, "invoice_tax_rate")}
                auth="tax_rate"
                value={row.invoice_tax_rate}
              ></dataAuthority>
            </div>
          );
        },
      },
    },
    { title: "采购天数", field: "purchase_days", width: "90" },
    { title: "记录时间", field: "created_at", width: "160" },
    { title: "修改人", field: "create_user_text", width: "160" },
  ],
});

const diffNumber = (row, key) => {
  const old_key = `old_${key}`;
  if (!row[old_key] || row[old_key] == row[key]) {
    return "";
  } else {
    return "diff-class";
  }
};

const sameNumber = (row, key) => {
  const old_key = `old_${key}`;
  if (!row[old_key] || row[old_key] == row[key]) {
    return "hidden";
  } else {
    return "";
  }
};

const handleClose = () => {
  visible.value = false;
};

defineExpose({ open });
</script>
<style lang="scss">
.hidden {
  display: none;
}
.diff-class {
  color: #ff0000 !important;
}

.mytable-scrollbar {
  ::-webkit-scrollbar {
    width: 12px;
    height: 12px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 4px;
  }
}
</style>
